<?php

Loader::import('pspframework.utils.sessions.SessionHandlerInterface');
class DatabaseSession implements SessionHandlerInterface {
	protected $_model;

	protected $_timeout;

	public function __construct() {
		$modelName = Param::read('Session.handler.model');
		if (empty($modelName)) {
			$settings = array(
				'class' => 'session',
				'alias' => 'session',
				'table' => 'sessions',
			);
		} else {
			$settings = array(
				'class' => $modelName,
				'alias' => 'session',
			);
		}
		$this->_model = &ClassRegistry::init($settings);
		$this->_timeout = Param::read('Session.timeout') * 60;
	}

	public function open() {
		return true;
	}

	public function close() {
		return true;
	}

	public function read($id) {
		$sql ='[@@:LM '.$this->_model->name.']
		[@@:UM '.$this->_model->name.']
		[@@:QU select]
		[_select '.$this->_model->name.'.* ]
		[_from]
		[_table '.$this->_model->name.':yes]
		[_where '.$this->_model->name.'.'.$this->_model->primaryKey.' = "'.$id.'"]
		[_limit 1]';			
		$row = POP::exe($sql);			
		if (empty($row[0][$this->_model->alias]['data'])) {
			return false;
		}
		return $row[0][$this->_model->alias]['data'];
	}

	public function write($id, $data) {
		if (!$id) {
			return false;
		}
		$expires = time() + $this->_timeout;
		$record = compact('id', 'data', 'expires');
		$record[$this->_model->primaryKey] = $id;
		$is = $this->read($id);
        if( !empty($is) ) {		
			$query = array(
			'keyid'=>$id,
			'set'=>array($this->_model->alias=>$record)
			);
        } else {		
			$query = array($this->_model->alias=>$record);	
        }	
		$sql ='[@@:UM '.$this->_model->name.'][@@:QU save]';
		return POP::exe($sql,$query);
	}

	public function destroy($id) {
		$query = array($this->_model->primaryKey =>$id);			
		$sql ='[@@:UM '.$this->_model->name.'][@@:QU del]';
        return POP::exe($sql,$query);		
	}

	public function gc($expires = null) {
		if (!$expires) {
			$expires = time();
		}
		$query = array('conditions'=>array($this->_model->alias . ".expires <" => $expires));			
		$sql ='[@@:UM '.$this->_model->name.'][@@:QU del]';
		return POP::exe($sql,$query);	
	}
}
?>